<script setup>
import {reactive, ref} from "vue";
import {POST, PUT} from "../../api/index.js";
import {notify} from "../../utils/commonScript.js";

const emit = defineEmits(['ok'])
const dialogVisible = ref(false)
const title = ref('新增')
const ruleFormRef = ref()
const ruleForm = reactive({
  id: '',
  title: '',
  endDate: ''
})
const rules = reactive({
  title: [
    { required: true, message: '请输入任务名称', trigger: 'blur' },
    { min: 1, max: 25, message: '长度1-25', trigger: 'blur' },
  ],
  endDate: [
    {
      type: 'date',
      required: true,
      message: '请选择',
      trigger: 'change',
    },
  ],
})


const open = (row) => {
  dialogVisible.value = true
  if(row){
    ruleForm.id = row.id
    ruleForm.title = row.title
    ruleForm.endDate = row.endDate
    title.value = '编辑'
  } else {
    title.value = '新增'
    ruleForm.id = ''
  }
}

const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if(ruleForm.id){
        PUT('/market/task', {
          id: ruleForm.id,
          title: ruleForm.title,
          endDate: ruleForm.endDate
        }).then(res => {
          notify('修改成功')
          dialogVisible.value = false
          emit('ok')
        })
      } else {
        POST('/market/task', {
          title: ruleForm.title,
          endDate: ruleForm.endDate
        }).then(res => {
          notify('保存成功')
          dialogVisible.value = false
          emit('ok')
        })
      }

    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
  dialogVisible.value = false
}

const disabledDate = (time) => {
  return time.getTime() < Date.now()
}

defineExpose({
  open
})

</script>

<template>
  <el-dialog v-model="dialogVisible" :title="title" width="800">
    <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        status-icon
    >
      <el-form-item label="任务名称" prop="title">
        <el-input v-model="ruleForm.title" />
      </el-form-item>
      <el-form-item label="结束日期" prop="endDate">
        <el-date-picker
            style="width: 100%;"
            v-model="ruleForm.endDate"
            type="date"
            value-format="YYYY-MM-DD"
            :disabled-date="disabledDate"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">

</style>
